﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using PMP.Common;
using PMP.Data;
using PMP.Models;
using PMP.Models.Shared;
using PMP.Models.ViewModel;

namespace PMP.Controllers
{
    public class ExamController : Controller
    {
        private readonly PMPContext _context;

        public ExamController(PMPContext context)
        {
            this._context = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Manager()
        {
            return View();
        }

        public IActionResult ExamLib()
        {
            var list = _context.Exam.OrderBy(x => x.Name).ToList();
            ViewBag.list = list;
            return View();
        }

        public IActionResult QuestLib()
        {
            return View();
        }

        public async Task<IActionResult> ExamEditAsync(int ID)
        {
            var exam = await _context.Exam.FirstOrDefaultAsync(x => x.ID == ID);
            if (exam == null)
            {
                exam = new Exam() { ID = 0, Name = "" };
            }
            ViewBag.exam = exam;
            return View();
        }

        public async Task<IActionResult> ExamSave(Exam exam)
        {
            if (string.IsNullOrEmpty(exam.Name))
            {
                return Json(new { success = false, msg = "名称不能为空" });
            }
            if (await _context.Exam.AnyAsync(x => x.Name == exam.Name))
            {
                return Json(new { success = false, msg = "名称重复" });
            }
            EntityEntry<Exam> entityEntry;
            if (exam.ID == 0)
            {
                entityEntry = _context.Exam.Add(exam);
            }
            else
            {
                entityEntry = _context.Exam.Update(exam);
            }
            try
            {
                await _context.SaveChangesAsync();
                var entity = entityEntry.Entity;
                if (entity.ID > 0)
                {
                    return Json(new { success = true, msg = "保存成功", data = new { exam = entity } });
                }
                else
                {
                    return Json(new { success = false, msg = "添加失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }

        public async Task<IActionResult> ExamQuest(int ID)
        {
            List<Exam> exams = await _context.Exam.Where(x => x.ID == ID).ToListAsync();
            if (exams.Count == 0)
            {
                return BadRequest("无效的数据");
            }
            string sql = @"
            --declare @id int
            select r.[ID], r.[EID], r.[QID], r.[Order], q.[Title], q.[OptionA], q.[OptionB], q.[OptionC], q.[OptionD], q.[Answer], q.[Analysis], q.[Point]
            from ExamQuestRel r
            inner join Quest q on r.qid= q.id
            where r.eid = @id
            order by r.[Order]
            ";
            List<SqlParameter> listp = new List<SqlParameter>();
            listp.Add(new SqlParameter("@id", ID));
            List<ViewExamQuest> list = await _context.ViewExamQuest.FromSqlRaw(sql, listp.ToArray()).ToListAsync();
            ViewBag.exam = exams[0];
            ViewBag.list = list;
            return View();
        }

        public async Task<IActionResult> QuestLib_trs(int id, string title, string all, int lastid)
        {
            List<Quest> list = new List<Quest>();
            if (id > 0)
            {
                list = await _context.Quest.Where(x => x.ID == id).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(title))
            {
                list = await _context.Quest.Where(x => x.Title.Contains(title)).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(all))
            {
                list = await _context.Quest.Where(x => x.Title.Contains(all) || x.OptionA.Contains(all) || x.OptionB.Contains(all) || x.OptionC.Contains(all) || x.OptionD.Contains(all) || x.Answer.Contains(all) || x.Analysis.Contains(all) || x.Point.Contains(all)).ToListAsync();
            }
            else
            {
                list = await _context.Quest.ToListAsync();
            }
            ViewBag.list = list;
            return View();
        }

        public async Task<IActionResult> QuestLib_trs20(int id, string title, string all, int lastid)
        {
            List<Quest> list = new List<Quest>();
            if (id > 0)
            {
                list = await _context.Quest.Where(x => x.ID == id).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(title))
            {
                list = await _context.Quest.Where(x => x.Title.Contains(title)).Take(20).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(all))
            {
                list = await _context.Quest.Where(x => x.Title.Contains(all) || x.OptionA.Contains(all) || x.OptionB.Contains(all) || x.OptionC.Contains(all) || x.OptionD.Contains(all) || x.Answer.Contains(all) || x.Analysis.Contains(all) || x.Point.Contains(all)).Take(20).ToListAsync();
            }
            else
            {
                list = await _context.Quest.Take(20).ToListAsync();
            }
            ViewBag.list = list;
            return View();
        }

        public async Task<IActionResult> QuestEdit(int ID = 0)
        {
            var quest = await _context.Quest.FirstOrDefaultAsync(x => x.ID == ID);
            if (quest == null)
            {
                quest = new Quest();
            }
            ViewBag.quest = quest;
            return View();
        }

        public IActionResult QuestComp()
        {
            return View();
        }

        public async Task<IActionResult> QuestSave(Quest quest)
        {
            try
            {
                if (quest.ID != 0)
                {
                    return BadRequest("添加数据时ID应为0");
                }
                if (string.IsNullOrEmpty(quest.Title))
                {
                    return BadRequest("题目不能为空");
                }
                if (string.IsNullOrEmpty(quest.OptionA))
                {
                    return BadRequest("选项A不能为空");
                }
                if (string.IsNullOrEmpty(quest.OptionB))
                {
                    return BadRequest("选项B不能为空");
                }
                if (string.IsNullOrEmpty(quest.OptionC))
                {
                    return BadRequest("选项C不能为空");
                }
                if (string.IsNullOrEmpty(quest.OptionD))
                {
                    return BadRequest("选项D不能为空");
                }
                if (!new string[] { "A", "B", "C", "D" }.Contains(quest.Answer))
                {
                    return BadRequest("请设置正确答案");
                }
                if (string.IsNullOrEmpty(quest.Analysis))
                {
                    return BadRequest("解析不能为空");
                }
                if (string.IsNullOrEmpty(quest.Point))
                {
                    return BadRequest("要点不能为空");
                }
                if (await _context.Quest.AnyAsync(x => x.Title == quest.Title))
                {
                    return BadRequest("题目有重复");
                }
                EntityEntry<Quest> entityEntry;
                entityEntry = _context.Quest.Add(quest);
                await _context.SaveChangesAsync();
                var entity = entityEntry.Entity;
                if (entity.ID > 0)
                {
                    return Json(new { msg = "保存成功", quest = entity });
                }
                else
                {
                    return BadRequest("添加失败");
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        public async Task<IActionResult> ExamQuestRel(int ID)
        {
            if (!await _context.Exam.AnyAsync(x => x.ID == ID))
            {
                return this.Err("无效的数据");
            }
            Exam exam = await _context.Exam.SingleOrDefaultAsync(x => x.ID == ID);
            if (exam == null)
            {
                return BadRequest("无效的数据");
            }
            var result = await (from r in _context.ExamQuestRel
                                join q in _context.Quest on r.QID equals q.ID
                                select r).ToListAsync();
            var listr = _context.ExamQuestRel.Where(x => x.EID == ID).Join<ExamQuestRel, Quest, int, ExamQuestRel>(_context.Quest, r => r.QID, q => q.ID, (r, q) => r).ToListAsync();
            var listq = _context.ExamQuestRel.Where(x => x.EID == ID).Join<ExamQuestRel, Quest, int, Quest>(_context.Quest, r => r.QID, q => q.ID, (r, q) => q).ToListAsync();

            ViewBag.exam = exam;
            ViewBag.listr = listr;
            ViewBag.listq = listq;
            return View();
        }

        public async Task<IActionResult> RemoveRel(ExamQuestRel rel)
        {
            try
            {
                if (!_context.ExamQuestRel.Any(x => x.ID == rel.ID))
                {
                    return BadRequest("无效的数据");
                }
                _context.ExamQuestRel.Remove(rel);
                await _context.SaveChangesAsync();
                return Json(new { msg = "移除成功" });
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        public async Task<IActionResult> AddRel(int eid, string ids)
        {
            if (string.IsNullOrEmpty(ids))
            {
                return BadRequest("请输入问题ID");
            }
            string[] arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries);
            var tran = _context.Database.BeginTransaction();
            int oknum = 0;
            foreach (string s in arr)
            {
                if (int.TryParse(s, out int id))
                {
                    bool anyq = await _context.Quest.AnyAsync(x => x.ID == id);
                    bool hasrel = await _context.ExamQuestRel.AnyAsync(x => x.EID == eid && x.QID == id);
                    if (hasrel)
                    {
                        continue;
                    }
                    int order = await _context.ExamQuestRel.CountAsync(x => x.ID == id);
                    ExamQuestRel rel = new ExamQuestRel { ID = 0, EID = eid, QID = id, Order = order };
                    await _context.AddAsync(rel);
                    await _context.SaveChangesAsync();
                    oknum++;
                }
            }
            await tran.CommitAsync();
            return Json(new { msg = $"成功添加了{oknum}条数据" });
        }

        public async Task<IActionResult> RelSort(int ID)
        {
            Exam exam = await _context.Exam.SingleOrDefaultAsync(x => x.ID == ID);
            if (exam == null)
            {
                return BadRequest("无效的数据");
            }
            var list = await (from r in _context.ExamQuestRel
                              join q in _context.Quest on r.QID equals q.ID
                              orderby r.Order
                              select new { r = r, q = q }).ToListAsync();
            ViewBag.exam = exam;
            ViewBag.list = list;
            return View();
        }
    }
}